<template>
 <div class="wrapper">
    <div class="header">
      最近联系人
      <img @click="showWarp()" src="../assets/img/icon_navigation@3x.png" alt="">
    </div>
    <ul class="list-out">
      <!--联系人/群-->
      <li v-for="item in rencentChats" v-if="item" @click.stop="goSession(item)" :class="!item.MsgFlag&&item.UnreadMsgCount>0?'userItem unread':'userItem'">
        <!--最近联系人-->
        <mt-cell-swipe :right="[{content: '删除',style: { background: 'red', color: '#fff' },handler: () => deleteContact(item)}]" v-if="item.Type == 1 || item.type == 'C2C'">
            <img :onerror="defaultImg" :src="item.C2cImage?item.C2cImage:c2cHead">
            <div class="userItemText">
              <div class="user">{{item.C2cNick?item.C2cNick:item.id}}<time>{{transTime(item.MsgTimeStamp,'')}}</time></div>
              <p>{{item.MsgShow}}</p>
            </div>
        </mt-cell-swipe>
        <!--最近联系群-->
        <mt-cell-swipe :right="[{content: '删除',style: { background: 'red', color: '#fff' },handler: () => deleteContact(item)}]" v-else>
            <img :onerror="defaultGroupImg" :src="item.GroupImage?item.GroupImage:groupHead">
            <div class="userItemText">
              <div class="user">{{item.GroupNick?item.GroupNick:item.id}}<time>{{transTime(item.MsgTimeStamp,'')}}</time></div>
              <p>{{item.MsgShow}}</p>
            </div>
        </mt-cell-swipe>
      </li>
    </ul>

    <mt-popup v-model="popupVisible" class="wrap" position="right">
      <div class="menuWrap">
        <div class="menu">
          <ul>
            <li class="menuLi" @click="goLink('/friendAdd')"><img src="../assets/img/icon_addfriend@3x.png">加好友/群</li>
            <li class="menuLi" @click="goLink('/AddressList')"><img src="../assets/img/icon_friend@3x.png">好友</li>
            <li class="menuLi" @click="goLink('/AddressList?type=1')"><img src="../assets/img/icon_group@3x.png">群组</li>
            <!--<li class="menuLi" @click="goLink('')"><img src="../assets/img/icon_system@3x.png">系统消息</li>-->
            <li class="menuLi menuLiLast" @click="goLink('/Setting')"><img src="../assets/img/icon_gear@3x.png">设置</li>
          </ul>
        </div>
      </div>
    </mt-popup>

 </div>

</template>
<script>
import {checkStatus} from '../assets/js/login';
import { Toast,Popup,CellSwipe } from 'mint-ui';
import Client from '../assets/js/common';
import convertMsgtoHtml from '../assets/js/convertMsg';
import Chat from '../assets/js/chat';
import c2cHead from '../assets/img/my@3x.png';
import groupHead from '../assets/img/the@3x.png';
export default {
  data () {
    return {
      popupVisible: false,
      loginInfo:{},
      rencentChats:null,
      c2cHead,
      groupHead,
      transTime:Client.transTime,
      defaultImg:Client.defaultImg,
      defaultGroupImg:Client.defaultImg
    }
  },
  created () {
    checkStatus((loginInfo)=>{
      this.loginInfo = loginInfo;
      this.getRencent();
    });
  },
  mounted(){
    this.setHeight();
  },
  components: {
   'mtPopup':Popup,'mtCellSwipe':CellSwipe
  },
  methods: {
    // 链接地址跳转
    goLink(link){
      this.$router.push(link);
    },
    showWarp() {
      this.popupVisible = true;
    },
    //获取未读c2c消息
		getMsgNotify(){
			webim.syncMsgs(
				resp => {
            let sessMap = webim.MsgStore.sessMap();
            if(this.rencentChats){
              for(let i in sessMap) {
                let items = sessMap[i]._impl;
                this.rencentChats.forEach((ele,i) => {
                  if(items.id == ele.id){
                    ele.UnreadMsgCount = items.unread;
                  }
                });
              }
            }
            //好友缺少的字段或信息从好友资料里拿
            Chat.getAllFriend(this.loginInfo.identifier).then(res => {
              if(res == null) return;
              this.infoMap = res.InfoItem;
              //console.log('this.infoMap',this.infoMap);
              Client.setStore('infoMap',res.InfoItem);
              if(this.rencentChats){
                this.getFriendInfo(this.rencentChats);
              }
            });
				},
				err => {
          Client.errInfo();
          //alert(err.ErrorInfo);
        }
			);
		},
		//获取最近联系人
		getRencent(){
			webim.getRecentContactList({
				'Count': 50 //最近的会话数 ,最大为100
			},resp => {
        let rencentOri = resp.SessionItem;
        //为了之后便于处理，将私聊To_Account以及群聊ToAccount统一成id字段
        let hasGroupMsg = false;
        if(rencentOri){
          this.rencentChats = rencentOri.filter((item)=>{
              if(item.Type == 1){
                item.id = item.To_Account;
              }else{
                item.id = item.ToAccount;
                hasGroupMsg = true;
              }
              //云通信会将一周前的聊天记录全清空,此时过滤零记录联系人
              return item.MsgTimeStamp !== 0;
          });
          //如果联系人中存在群组,另外处理群接收但不提示消息的状态
          if(hasGroupMsg){
            Chat.getMyGroup(this.loginInfo.identifier).then(resp=>{
              //console.log('群组资料',resp);
              this.myGroupInfo = resp;
              //设置了接收但不提示消息的群
              let groupAcceptMsg = [];
              resp.forEach((item)=>{
                if(item.SelfInfo && item.SelfInfo.MsgFlag == 'AcceptNotNotify'){
                  this.rencentChats.forEach((val)=>{
                    if(val.ToAccount == item.GroupId){
                      val.MsgFlag = 'AcceptNotNotify';
                      groupAcceptMsg.push(item.GroupId);
                      //console.log('匹配到的群组',val)
                    }
                  })
                }
              });   
              this.groupMsgFlag = groupAcceptMsg;          
            });
          }
        }  
        this.getMsgNotify();
				//业务处理
			},resp => {
        Client.errInfo();
        console.log(resp)
				//错误回调
      });
		},
		//删除最近联系人
		deleteContact(item){
      //Type最近联系人类型,type未读消息联系人类型
      let newType = item.Type || item.type;
      if(newType == 'C2C'){
        newType = 1;
      }
      if(newType == 'GROUP'){
        newType = 2;
      }
			let dataContact = {
				'To_Account': item.id,
				'chatType': newType
      }
			webim.deleteChat(
				dataContact,
				resp => {
          //要操作的数据对象（最近联系人还是未读信息联系人）
          if(item.UnreadMsgCount>0){
            //假如是未读消息联系人,设置消息已读
						let selSess = webim.MsgStore.sessByTypeId(item.type, item.id);
						webim.setAutoRead(selSess, true, true);
          }
          this.rencentChats.forEach((ele,i)=>{
            if(ele.id == item.id){
              this.rencentChats.splice(i,1);
            }
          });
					//console.log('删除联系人成功',dataContact);
				},
				resp => {
          Client.errInfo();
					console.log('删除联系人失败',resp);
				}
			);
		},
		//跳转未读消息聊天
		goNews(item){
			this.$router.push({path: "/session", query:{id: item.id,selType:item.type}});
		},
		//跳转最近联系人聊天
		goSession(item){
      let newTypes = 'C2C';
      if(item.Type == 2 || item.type == 'GROUP'){
          newTypes = 'GROUP';
			}
      this.$router.push({path: "/session", query:{id: item.id,selType:newTypes}});
		},
    /*transTime(time){
      let getTimes = new Date(parseInt(time) * 1000).toLocaleString().replace(/:\d{1,2}$/,'');
      return getTimes.replace(/[^\s]+/,'');
    },*/
    compare(property){
         return (obj1,obj2) => {
             let value1 = obj1[property],
                 value2 = obj2[property];
             return value2 - value1;
         }
    },
    getFriendInfo(oriArr){
      let test88 = oriArr instanceof Array;
      if(this.infoMap){
        if(oriArr instanceof Array){
          oriArr.forEach((val) => {
            if(val.Type == 1){
              this.matchInfo(val);
            }
          });
        }else{
          this.matchInfo(oriArr);
        }
      }
    },
    //从缓存好友表里匹配数据
    matchInfo(val){
      this.infoMap.forEach((item,index) => {
              if(item.SnsProfileItem){
                item.SnsProfileItem.find((list)=>{
                  if(item.Info_Account == val.id){
                    if(list.Tag == 'Tag_Profile_IM_Image'){
                       val.C2cImage = list.Value;
                    }else if(list.Tag == 'Tag_Profile_IM_Nick'){
                       val.C2cNick = list.Value;
                    }
                  }
                });
              }
      });
    },
    setHeight(){
      let topH = document.querySelector('.header').offsetHeight;
      let contentH = document.querySelector('.list-out');
      contentH.style.height = window.innerHeight - topH + 'px';
    }
  },
	watch:{
    'loginInfo.onMsgNotify':function(val){
			  if(val == null){
				  return
			  }else{
          //console.log('监听回来的消息',val);
          let unReadObj = val.sess._impl;
          let transObj = convertMsgtoHtml(val);
          unReadObj.MsgShow = Client.transNews(transObj);
          unReadObj.MsgTimeStamp = unReadObj.time;
          //监听回来的未读群消息unread记录为0?
          unReadObj.UnreadMsgCount = 1;
          if(unReadObj.type == 'C2C'){
            //console.log('c2c2',unReadObj);
            this.getFriendInfo(unReadObj);
          }else{
            unReadObj.GroupNick = unReadObj.name;
            //如果存在有群设置了接收但不提示消息
            if(this.groupMsgFlag){
              this.groupMsgFlag.forEach((item,index)=>{
                if(unReadObj.id == item){
                  unReadObj.MsgFlag = 'AcceptNotNotify';
                }
              })
            }
            //检查替换群头像
            if(this.myGroupInfo){
              this.myGroupInfo.forEach((item)=>{
                if(item.GroupId == unReadObj.id){
                  unReadObj.GroupImage = item.FaceUrl;
                }
              })
            }
          }
          //console.log("处理后的unReadObj",unReadObj);
          //完全没任何数据直接添加
          if(!this.rencentChats){
            this.rencentChats = [];
            //console.log('初始回来的信息',unReadObj);
            this.rencentChats.push(unReadObj);
          }else{
            let hasExist = this.rencentChats.find((value, index, arr)=>{
              return value.id == unReadObj.id;
            });
            if(typeof hasExist == 'undefined'){
              this.rencentChats.unshift(unReadObj);
            }else{
              this.rencentChats.forEach((ele,i) => {
                if(unReadObj.id == ele.id){
                  this.rencentChats.splice(i,1,unReadObj);
                }
              });
              //sort
              this.rencentChats.sort(this.compare("MsgTimeStamp"));
            }
          }
			  }
    },

	}
}

</script>
<style lang="less">
.userItem{
  .mint-cell-swipe{
    width:100%;
    background:none !important;
  }
  .mint-cell-wrapper .mint-cell-title{
    display: none;
  }
  .mint-cell-wrapper .mint-cell-value{
    padding-left:.13rem;
  }
  .mint-cell-wrapper{
    padding:0;
    background-image:none;
  }
  .mint-cell-swipe-buttongroup .mint-cell-swipe-button{
    padding:0 .2rem;
    font-size:.14rem;
    line-height:.64rem;
  }
  &.unread .mint-cell-value:after{
    display:block;
    content:'';
    width:.06rem;
    height:.06rem;
    background:#EC5656;
    border-radius:.03rem;
    position: absolute;
    top:.12rem;
    left:.5rem;
  }
}
</style>
<style lang="less" scoped>
.wrapper {
  background-attachment: #fff;
  .wrap {
    right: 0.08rem !important;
    top: 1.38rem !important;
    background:none;
    .menuWrap {
      width: 1.3rem;
      position: relative;
      &:before{
        width:0;
        height:0;
        display:block;
        content:'';
        border-width:.06rem;
        border-style:solid;
        border-color: transparent transparent #fff transparent;
        position:absolute;
        right:.1rem;
        top:-.12rem;
      }
      .menu {
        width: 1.3rem;
        background-color: white;
        border-radius:.03rem;
        overflow: hidden;
        .menuLi {
          height: 0.39rem;
          border-bottom: 1px solid #E1E1E1;
          display: flex;
          align-items: center;
          img {
            width: 0.14rem;
            height: 0.14rem;
            margin-left: 0.17rem;
            margin-right: 0.1rem;
          }
        }
        .menuLiLast {
          border: none;
        }

      }
    }
  }

  .header {
    width: 100%;
    height: 0.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    font-size: 0.16rem;
    border-bottom: 1px solid #f4f4f4;
    background-color: white!important;
    img {
      width: 0.2rem;
      height: 0.14rem;
      position: absolute;
      right: 0.15rem;
      top: 50%;
      margin-top: -0.07rem;
    }
  }
  .list-out{
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch; 
    background:#fff;
    .userItem {
      height: 0.64rem;
      /*margin: 0 0.13rem;*/
      display: flex;
      align-items: center;
      background:#fff;
      img {
        width: 0.44rem;
        height: 0.44rem;
        border-radius: 50%;
      }
      .userItemText {
        width: 2.97rem;
        height: 0.65rem;
        margin-left: 0.1rem;
        border-bottom: 1px solid #E1E1E1;
        padding: 0.12rem 0;
        box-sizing: border-box;
        .user {
          height: 0.2rem;
          line-height: 0.2rem;
          color: #4A4A4A;
          font-size: 0.14rem;
          overflow: hidden;
          time {
            float: right;
            font-size: 11px;
            color: #818181;
          }
        }
        p {
          height: 0.2rem;
          line-height: 0.2rem;
          color: #818181;
          font-size: 12px;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
      }
      &:last-child{
        .userItemText {
          border:0;
        }
      }
    }
  }
  
}
</style>
